package com.windbell.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.windbell.service.NewsService;
import com.windbell.util.PagerBean;

public class NewsAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public enum Method{
			list(0),
			context(1);
			private final int id;
			Method(int id) { this.id = id; }
		    public int getValue() { return id; }
	}
	public NewsAction() {
		super();
	}
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		NewsService newsService = (NewsService) getBean("newsService");
		
		Object m =request.getParameter("method");
		int method =Method.list.getValue();
		try {
			method=Integer.parseInt(m+"");
		} catch (NumberFormatException e) {
			method =Method.list.getValue();
		}
		if(method==Method.list.getValue()){
			List list = newsService.list();
			PagerBean pager = new PagerBean(list.size(), list);
			buildResult(response, pager);
		}else if(method==Method.context.getValue()){
			Object aurl =request.getParameter("aurl");
			Map  map =new HashMap();
			map.put("aurl", aurl);
			Map list = newsService.context(map);
			buildResult(response, list);
		}
		
		
	}

	public void buildResult(HttpServletResponse response, Object value) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			new ObjectMapper().writeValue(writer, value);
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (Exception e) {
				writer = null;
			}
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	public Object getBean(String name) {
		WebApplicationContext webApplicationContext = WebApplicationContextUtils
				.getWebApplicationContext(this.getServletContext());
		return webApplicationContext.getBean(name);
	}

}
